import {Component, forwardRef, OnInit} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import * as _ from 'lodash';

export const LOCATION_LIST_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => LocationListComponent),
    multi: true
};

@Component({
    selector: 'kylin-location-list',
    templateUrl: './location-list.component.html',
    styleUrls: ['./location-list.component.less'],
    providers: [LOCATION_LIST_VALUE_ACCESSOR]
})

export class LocationListComponent implements OnInit, ControlValueAccessor {

    locations = [];

    locationSelectedValue = '度';

    value: any;

    private target1 = '°';
    private target2 = '′';
    private target3 = '″';

    propagateChange = (data: any) => {
    };


    constructor() {

    }

    ngOnInit() {
    }

    /**
     * // todo this.locations的值经过测试 如果为[{},{}] 数组中多个对象这种格式,传递的值就为一个空数组,目前的解决办法就是变成字符串,提交时候在解析回来(有空时候找到原因)
     */
    inputGroupValueChange() {
        this.propagateChange(JSON.stringify(this.locations)); // 双向绑定
    }

    writeValue(value: any) { // 该方法用于将模型中的新值写入视图或 DOM 属性中
        if (!_.isEmpty(value)) {
            this.locations = value;
            this.defaultLocationSelectedValueInit(this.locations[0].eastLongitude);
        } else {
            this.locations = [{
                'num': 1,
                'eastLongitude': '',
                'northLatitude': '',
                'altitude': ''
            }]
        }
    }

    registerOnChange(fn: (data: any) => void): void {
        this.propagateChange = fn;
    }

    registerOnTouched(fn: any) {
    }

    locationPlus() {
        if (this.locations.length < 10) {
            this.addLocation();
        }
    }

    locationMinus(id) {
        const targetLocations = [];
        this.locations.map(i => {
            if (Number(i.num) !== Number(id)) {
                targetLocations.push(i);
            }
        });
        this.locations = targetLocations;
        this.inputGroupValueChange();
    }

    addLocation() {
        let newId = 1;
        if (this.locations.length > 0) {
            newId = Number(_.last(this.locations).num) + 1;
        }
        this.locations.push({num: newId, eastLongitude: '', northLatitude: '', altitude: ''});
    }

    defaultLocationSelectedValueInit(value: string) {
        if (value.indexOf(this.target1) !== -1) {
            this.locationSelectedValue = '度';
        }
        if (value.indexOf(this.target2) !== -1) {
            this.locationSelectedValue = '度分';
        }
        if (value.indexOf(this.target3) !== -1) {
            this.locationSelectedValue = '度分秒';
        }
    }

}
